package models

import (
	"github.com/goravel/framework/database/orm"
	"github.com/goravel/framework/facades"
)

type User struct {
	orm.Model
	Username string `json:"username"`
	Email    string `json:"email"`
	Password string `json:"password"`
	Status   uint8  `json:"status"`
	IsRoot   uint8  `json:"is_root"`
	orm.SoftDeletes
	orm.Timestamps

	// 关联关系
	Roles []Role `json:"roles" gorm:"many2many:user_roles;"`
}

func (r *User) TableName() string {
	return "users"
}

// GetRoles 获取用户角色
func (u *User) GetRoles() ([]Role, error) {
	var roles []Role
	err := facades.Orm().Query().
		Table("roles").
		Join("user_roles", "roles.id", "=", "user_roles.role_id").
		Where("user_roles.user_id", u.ID).
		Find(&roles)
	return roles, err
}

// GetPermissions 获取用户权限
func (u *User) GetPermissions() ([]Permission, error) {
	var permissions []Permission

	// 如果是超级用户，返回所有权限
	if u.IsRoot == 1 {
		err := facades.Orm().Query().Find(&permissions)
		return permissions, err
	}

	err := facades.Orm().Query().
		Table("permissions").
		Join("role_permissions", "permissions.id", "=", "role_permissions.permission_id").
		Join("user_roles", "role_permissions.role_id", "=", "user_roles.role_id").
		Where("user_roles.user_id", u.ID).
		Find(&permissions)

	return permissions, err
}

// HasPermission 检查用户是否有指定权限
func (u *User) HasPermission(permissionKey string) (bool, error) {
	// 如果是超级用户，直接返回true
	if u.IsRoot == 1 {
		return true, nil
	}

	var count int64
	err := facades.Orm().Query().
		Table("users").
		Join("user_roles", "users.id", "=", "user_roles.user_id").
		Join("role_permissions", "user_roles.role_id", "=", "role_permissions.role_id").
		Join("permissions", "role_permissions.permission_id", "=", "permissions.id").
		Where("users.id", u.ID).
		Where("permissions.perm_key", permissionKey).
		Count(&count)

	return count > 0, err
}

// HasRole 检查用户是否有指定角色
func (u *User) HasRole(roleName string) (bool, error) {
	// 如果是超级用户，直接返回true
	if u.IsRoot == 1 {
		return true, nil
	}

	var count int64
	err := facades.Orm().Query().
		Table("users").
		Join("user_roles", "users.id", "=", "user_roles.user_id").
		Join("roles", "user_roles.role_id", "=", "roles.id").
		Where("users.id", u.ID).
		Where("roles.role_name", roleName).
		Count(&count)

	return count > 0, err
}
